package com.jy.appmarket.network.task;

import android.content.Context;
import android.os.Handler;

import com.jy.appmarket.network.engine.BaseNetEngine;

/**
 * 类说明：
 * 
 * @author Terry.Lu
 * @date 2013-5-15
 * @version 1.0
 */
public class NetTask implements Runnable {
	// private static final String TAG = "NetTask";

	private BaseNetEngine mEngine = null;
	private int mTag = 0;
	private static Handler mHandler = new Handler();
	private Context mContext = null;
	private int mStatus = -1; // 0 means ok, -1 means error
	private NetTaskListener mListener = null;
	private boolean mIsCancel = false;

	private boolean mIsTaskRunning = false;

	public NetTask(Context c, BaseNetEngine engine, int tag) {
		mContext = c;
		mEngine = engine;
		mTag = tag;
	}

	public void setListener(NetTaskListener l) {
		mListener = l;
	}

	public void cancel() {
		mIsCancel = true;
		mEngine.cancel();
	}

	public boolean isTaskRunning() {
		return mIsTaskRunning;
	}

	@Override
	public void run() {
		mIsTaskRunning = true;
		mIsCancel = false;
		if (mEngine.getNetData(mContext)) {
			mStatus = 0;
		} else {
			mStatus = -1;
		}
		mHandler.post(mCallbackRunnable);
	}

	private Runnable mCallbackRunnable = new Runnable() {

		@Override
		public void run() {
			mIsTaskRunning = false;
			if (mListener == null) {
				return;
			}

			if (mIsCancel) {
				mListener.onTaskRunCanceled(mTag);
				return;
			}

			if (mStatus == 0) {
				mListener.onTaskRunSuccessful(mTag, mEngine);
			} else if (mStatus == -1) {
				mListener.onTaskRunError(mTag);
			}

		}
	};

	public interface NetTaskListener {

		void onTaskRunSuccessful(int tag, BaseNetEngine engine);

		void onTaskRunError(int tag);

		void onTaskRunCanceled(int tag);
	}
}
